package top.freemakerDemo.servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import top.freemakerDemo.utils.WordUtil;

@WebServlet("/downloadResume")
public class Servlet4Download extends HttpServlet{

	private static final long serialVersionUID = 1L;
	@Override  
    protected void service(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {  
        req.setCharacterEncoding("utf-8");  
        Map<String, Object> map = new HashMap<String, Object>(); 
        //获取表单控件的names
        Enumeration<String> paramNames = req.getParameterNames();  
        // 通过循环将表单参数放入键值对映射中  
        while(paramNames.hasMoreElements()) {  
        	//获取控件name
            String key = paramNames.nextElement();  
            //获取name为key的控件的value
            String value = req.getParameter(key); 
            //验空，如果有未填写的内容会报错，所以检测出来强制修改为“无”
            if (value.equals("")||value==null) {
				value="无";
			}
            map.put(key, value);  
        }  
      
        File file = null;  
        InputStream in = null;  
        ServletOutputStream out = null;  
        try {  
            // 调用工具类WordUtil的createDoc方法生成Word文档  
            file = WordUtil.createDoc(map, "resume");  
            in = new FileInputStream(file);  
              
            resp.setCharacterEncoding("utf-8");  
            resp.setContentType("application/msword");  
            // 设置浏览器以下载的方式处理该文件默认名为resume.doc  
            resp.addHeader("Content-Disposition", "attachment;filename=resume.doc");  
              
            out = resp.getOutputStream();  
            byte[] buffer = new byte[1024];  // 缓冲区  
            int bytesToRead = -1;  
            // 通过循环将读入的Word文件的内容输出到浏览器中  
            while((bytesToRead = in.read(buffer)) != -1) {  
                out.write(buffer, 0, bytesToRead);  
            }  
        } finally {  
            if(in != null) in.close();  
            if(out != null) out.close();  
            if(file != null) file.delete(); // 删除临时文件  
        }  
    }
 
}
